package com.qiniuyun.backai.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qiniuyun.backai.common.Constant;
import com.qiniuyun.backai.model.dto.UserDto;
import com.qiniuyun.backai.model.pojo.User;
import com.qiniuyun.backai.service.UserService;

import com.qiniuyun.backai.util.CacheUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
@Slf4j
public class myInterceptor implements HandlerInterceptor {
    private final UserService userservice;
  @Autowired
  private CacheUtil cacheUtil;
    public myInterceptor(UserService userservice) {
        this.userservice = userservice;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserDto user = (UserDto) request.getSession().getAttribute(Constant.SESSION_KEY);
        if (user != null) {
            //request中的session的user
            String username = user.getUsername();
            String password = user.getPassword();
            //从缓存中获取user
            User user1=null;
             user1= cacheUtil.map.get(username);
            //缓存中不存在从数据库中拿
            if(user1==null){
                QueryWrapper<User> wrapper = new QueryWrapper<User>()
                        .eq("username", username)
                        .eq("password",password);
                user1 = userservice.getOne(wrapper);
            }
            if (user1 == null) {
                log.error("未获取到user {},请注册", user1);
                return false;
            }
            //判断两者是否相等
            if (!(username.equals(user1.getUsername())&&(password.equals(user1.getPassword())))) {
                log.error("两者不相同");
                return false;
            }
            return true;
        }
        log.error("请登录");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        log.info("拦截器结束");
    }
}
